#include "mstdio.h"
#include <string.h>
#include <stdlib.h>

// For sys call
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>


mFILE* mfopen(const char* filename, const char* mode){
    if(!filename) return NULL;
    int fd = -1;
    if(0 == strcmp(mode , "r")){
        fd = open(filename, O_RDONLY);
    }
    else if(0 == strcmp(mode, "w")){
        fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    }
    else if(0 == strcmp(mode, "a")){
        fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    }
    if(fd < 0) return NULL;

    mFILE* mf = (mFILE*)malloc(sizeof(mFILE));
    if(mf == NULL){
        close(fd);               
        return NULL;
    }
    
    mf->fileno = fd;
    mf->flag = FLUSH_LINE;
    mf->size = 0;
    mf->cap = BUF_SIZE;
    //为什么返回的是mFILE* 因为 用的是malloc，glibc里也是因此
    return mf;
}

void mfflush(mFILE* stream){
    if(stream && stream->size > 0){
        write(stream->fileno, stream->buffer, stream->size);
        stream->size = 0;
    }
}
int mfwrite(const void* ptr, int num, mFILE *stream){
    memcpy(stream->buffer + stream->size,ptr,num);
    stream->size += num;
    
    // 判断刷新
    if(stream->flag == FLUSH_LINE && stream->size >= 0 && \
            stream->buffer[stream->size - 1 == '\n'] )
    {
        mfflush(stream);
    }
}

void mfclose(mFILE* stream){
    if(stream && stream->size>0){
        fflush(stream);
    }
    close(stream->fileno);
}


